package com.wj.controller;

import com.wj.domain.dto.UserDTO;
import com.wj.domain.vo.UserVO;
import com.wj.service.UserService;
import com.wj.tool.common.utils.DeviceUtil;
import com.wj.tool.utils.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * @description: 
 * @author: wj
 * @create: 2022/5/12 14:29
 */
@Controller
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户登录
     */
    @RequestMapping(value = "login")
    public String Login(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        if (DeviceUtil.checkAgentIsMobile(userAgent)){
            // 移动端
            return "mobile/user/login";
        }
        return "login";
    }

    /**
     * 用户登录验证
     */
    @ResponseBody
    @RequestMapping(value = "loginV")
    public Result loginV(HttpServletRequest request, @RequestParam("username") String username, @RequestParam("password") String password){
        boolean b = userService.verificationUser(username, password);
        if (b){
            //创建session
            HttpSession session = request.getSession();
            UserVO user = userService.getUserByName(username);
            session.setAttribute("id",user.getId());
            session.setAttribute("username",username);
            session.setAttribute("password",password);
            return new Result(200,"登录成功");
        }
        return new Result(-1,"账号或密码不正确");
    }


    /**
     * 用户注册
     */
    @RequestMapping(value = "signin")
    public String SignIn(){

        return "signin";
    }
    /**
     * 用户注册验证
     */
    @ResponseBody
    @RequestMapping(value = "signinV")
    public Result signinV(@RequestParam("username") String username, @RequestParam("password") String password){
        boolean b = userService.verificationUserName(username);
        if (b){
            return  new Result(-1,"用户名已存在");
        }
        UserDTO user=new UserDTO();
        user.setUsername(username);
        user.setPassword(password);
        userService.save(user);
        return new Result(200,"注册成功");
    }
    /**
     * 用户注销
     */
    @RequestMapping(value = "logout")
    public ModelAndView Logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute("id");
        session.removeAttribute("username");
        session.removeAttribute("password");
        return new ModelAndView("redirect:index");
    }
}

